import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import gobject
import thread
import datetime


class WebHandler(BaseHTTPRequestHandler):
    
    def do_GET(self):
        if self.path == "/":
            self.show_index()
            return
        if self.path.endswith(".html"):
            self.show_page(self.path)
            return
        if self.path.endswith(".wav"):
            print "path ends with .wav"
            WebServer.instance().emit('send-audio', self.path)
            self.show_index("Broadcasted " + self.path + " at " + str(datetime.datetime.now()) + "<br/>")
            return
                
    def show_page(self, path, response_text=""):
        try:
            f = open(curdir + sep + "web/" + path) #self.path has /test.html
            #note that this potentially makes every file on your computer readable by the internet

            self.send_response(200)
            self.send_header('Content-type',	'text/html')
            self.end_headers()
            if response_text:
                self.wfile.write(response_text)
            self.wfile.write(f.read())
            f.close()
        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)
            
    def show_index(self, response_text=""):
        self.show_page("index.html", response_text) 
        
    def do_POST(self):
        clen = self.headers.getheader('content-length')
        if clen:
            clen = int(clen)
        else:
            print 'POST ERROR: missing content-length'
            return

        input_body = self.rfile.read(clen)
        data = cgi.parse_qs(input_body)
        
        if data['door']:
            # Someone at door
            WebServer.instance().emit('door',1)
            
        self.show_page("index.html")
        

        
class WebServer(gobject.GObject):
    __gsignals__ = {
        # Someone is at the door
        'door' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, 
                (gobject.TYPE_LONG,)),
        'send-audio' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, 
                (gobject.TYPE_STRING,)),
    }
    
    __instance = None
    
    @classmethod
    def instance(cls):
        if WebServer.__instance is None:
            WebServer.__instance = WebServer()
        return WebServer.__instance
        
    def __init__(self, ip):
        gobject.GObject.__init__(self)
        self.server = HTTPServer((ip, 8000), WebHandler)
        WebServer.__instance = self
        thread.start_new_thread(self.server.serve_forever, ())
        
    #def connect_signal(self, signal, callback):
    #    self.server.connect(signal, callback)
    
gobject.type_register(WebServer)
